package com.yansu.own.common;

import com.yansu.own.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

/**
 * 全局异常处理器
 */
@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})//扫描Controller和RestController类
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(CustomException.class)
    public ResponseResult<String> exceptionHandler(CustomException ex) {
        log.error(ex.getMessage());
        return ResponseResult.errorResult(ex.getMessage());
    }

    /**
     * 处理@Validated参数校验失败异常
     * @param exception 异常类
     * @return 响应
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<String> exceptionHandler(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        StringBuilder stringBuilder = new StringBuilder();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            if (errors != null) {
                errors.forEach(p -> {
                    FieldError fieldError = (FieldError) p;
                    log.warn("Bad Request Parameters: dto entity [{}],field [{}],message [{}]",fieldError.getObjectName(), fieldError.getField(), fieldError.getDefaultMessage());
                    stringBuilder.append(fieldError.getDefaultMessage());
                });
            }
        }
        return ResponseResult.errorResult(stringBuilder.toString());
    }

    @ExceptionHandler(Exception.class)
    public ResponseResult<String> ExceptionHandler(SQLIntegrityConstraintViolationException exception) {
        return ResponseResult.errorResult("未知错误");
    }
}
